<script>
export default {
  name: 'Tabs',
  props: {
    defaultName: {
      type: String || Number,
      default: 0,
    },
  },
  data() {
    return {
      currentName: this.defaultName,
      panes: [],
    };
  },
  methods: {
    calcPaneInstances(isForceUpdate = false) {
      if (this.$slots.default) {
        const paneSlots = this.$slots.default.filter(
          vnode => vnode.tag && vnode.componentOptions && vnode.componentOptions.Ctor.options.name === 'TabPane',
        );
        // update indeed
        const panes = paneSlots.map(({ componentInstance }) => componentInstance);
        const panesChanged = !(
          panes.length === this.panes.length && panes.every((pane, index) => pane === this.panes[index])
        );
        if (isForceUpdate || panesChanged) {
          this.panes = panes;
        }
      } else if (this.panes.length !== 0) {
        this.panes = [];
      }
    },
    setCurrentName(value) {
      if (this.currentName !== value) {
        this.currentName = value
      }
    },
  },
  render(createElement) {
    const { panes } = this;
    const header = createElement('tab-nav', {
      attrs: {
        panes,
      },
    });

    const panels = createElement(
      'div',
      {
        class: ['tabs-content'],
      },
      this.$slots.default,
    );

    return createElement(
      'div',
      {
        class: ['tabs'],
      },
      [header, panels],
    );
  },
  watch: {
    defaultName(val) {
      this.currentName = val;
    },
  },
  mounted() {
    this.calcPaneInstances();
  },
  updated() {
    this.calcPaneInstances();
  }
};
</script>

<style lang="stylus">
.tabs
  background-color: #2d2d2d
  overflow: hidden
</style>
